package com.hxkcloud.nurse.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.hxkcloud.nurse.YjhApplication;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * ProjectName: XANCApplication
 * PackageName: com.huatek.xanc.utils
 * Description: 网络工具类
 * Create by Allen_Lee.
 * Date: 2016/7/10 14:21
 */
public class WebUtils {

    public static boolean isConnected() {
        // 获取手机的连接服务管理器，这里是连接管理器类
        NetworkInfo.State wifiState = null;
        NetworkInfo.State mobileState = null;
        ConnectivityManager cm = (ConnectivityManager) YjhApplication
                .getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);

        wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();

        if (NetworkInfo.State.CONNECTED != wifiState && NetworkInfo.State.CONNECTED != mobileState) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * URL 编码
     * @param params
     * @param paramsEncoding
     * @return
     */
    public static String Urlencode(Map<String, Object> params, String paramsEncoding) {
        StringBuilder encodedParams = new StringBuilder();
        try {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
                encodedParams.append('=');
                encodedParams.append(URLEncoder.encode(entry.getValue().toString(), paramsEncoding));
                encodedParams.append('&');
            }
            return encodedParams.toString();
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
        }
    }

    /**
     * URL 编码
     * @param params
     * @param paramsEncoding
     * @return
     */
    public static String Urlencode(String params, String paramsEncoding) {
        StringBuilder encodedParams = new StringBuilder();
        try {
            encodedParams.append(URLEncoder.encode(params, paramsEncoding));
            return encodedParams.toString();
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
        }
    }

}
